#include "stdafx.h"
#include "BasicTower.h"
#include "Collider.h"
#include "EntityFactory.h"
#include "EntityManager.h"
#include "Projectile.h"
#include "TargetMediator.h"
#include "ResourceManager.h"
#include "Sound3D.h"

BasicTower::BasicTower(const EEntityType& entity_type, EntityFactory* entity_factory, EntityManager* entity_manager, TargetMediator* target_mediator) : Entity(entity_type), m_target_mediator(target_mediator){
	m_entity_factory = entity_factory;
	m_entity_manager = entity_manager;
	m_scan_collider = nullptr;
}


BasicTower::~BasicTower(void){
	m_target_mediator->RemoveTower(this);
	m_scan_collider->Destroy();
}

void BasicTower::Init(SceneObject* scene_object, Grid* grid){
	m_scene_object = scene_object;
	SetShootTime(2.0f);
	m_curr_shoot_time = 0.0f;

	m_shoot_sound = m_entity_factory->GetResouceManager()->GetSound3D("jaguar.wav");
	m_shoot_sound->SetVolume(1.0f);
	m_shoot_sound->SetMinMaxDistance(1.0f, 1000.0f);
	
}

void BasicTower::Update(float deltatime){
	Entity* target = m_target_mediator->GetTarget(this);
	if (m_curr_shoot_time <= 0.0f && target != nullptr){
		Shoot(target);
		m_curr_shoot_time = m_shoot_time;
	}
	else
		m_curr_shoot_time -= deltatime;

	// Update basic tower here
	m_scene_object->m_transform = DirectX::XMMatrixRotationRollPitchYaw(m_rotation.x, m_rotation.y, m_rotation.z) * DirectX::XMMatrixTranslation(m_position.x, m_position.y, m_position.z);

	// Move bounding sphere with entity
	m_scene_object->m_bounding_sphere.m_position.x = m_position.x;
	m_scene_object->m_bounding_sphere.m_position.y = m_position.y;
	m_scene_object->m_bounding_sphere.m_position.z = m_position.z;
	m_collider->Update(m_position);
	m_scan_collider->Update(m_position, target);

	m_shoot_sound->SetPosition(m_position);
}

void BasicTower::Shoot(Entity* target){
	Vector3 target_position = target->GetPosition();
	Vector3 direction = target_position - m_position;
	direction.Normalize();

	Entity* projectile = m_entity_factory->Create(Projectile_Type, m_grid);
	m_entity_manager->AddEntity(projectile);
	projectile->SetPosition(m_position);

	if (projectile->GetEntityType() == Projectile_Type){
		Projectile* p = static_cast<Projectile*>(projectile);
		p->SetDirection(direction);
	}
	projectile->Update(0.0f);
	
	m_shoot_sound->Play();
}

void BasicTower::SetShootTime(float shoot_time){
	m_shoot_time = shoot_time;
}